package com.nowcoder.community.controller;

import com.nowcoder.community.controller.exception.PageErrorException;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.SearchService;
import com.nowcoder.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("search")
public class SearchController {

    @Autowired
    SearchService searchService;

    @Autowired
    UserService userService;


    @PostMapping
    public String search(Model model, String keyword, Page page) {
        if (keyword == null || keyword.isEmpty()) {
            throw new PageErrorException("无效的参数.");
        }
        List<DiscussPost> discussPosts = searchService.searchDiscussPost(keyword, page);
        Map<Integer, User> userMap = new HashMap<>();
        for (DiscussPost discussPost : discussPosts) {
            userMap.put(discussPost.getUserId(), userService.findUserById(discussPost.getUserId()));
        }

        model.addAttribute("results", discussPosts);
        model.addAttribute("userMap", userMap);
        return "site/search";
    }
}
